const jwt = require('jsonwebtoken')
const Rsa = require('./Rsa')
const sign_code = 'siwi2017@siwi2017.abc'
const Util = require('./Util')
class Jwt {
    constructor() {

    }
    /**
     * 加密token
     * data :{id:'59a62b0b790c1a5ea72b1ea3', username: 'Mankong'}
     * @param {any} data 
     * @returns 
     * @memberof Jwt
     */
    async sign(data) {
        // 对签名数据加密
        let res = await Util.cipher(JSON.stringify(data.data))
        let token  = await jwt.sign({
            exp: data.exp ? data.exp: (Date.now() + 1000 * 86400 * 1) / 1000,
            data: res
        }, Rsa.private_key, { algorithm: 'RS256' })
        return token
    }
    /**
     * 验证token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async verify(token) {
        try {
            let data = await jwt.verify(token, Rsa.public_key, { algorithm: 'RS256' })
            let token_data = await Util.decipher(data.data)
            let res = {
                exp: data.exp,
                data: JSON.parse(token_data),
                iat: data.iat
            }
            return res
        } catch (error) {
            console.trace(error)
            return false
        }
    }

    /**
     * 解密token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async decode(token) {
        try {
            let data = jwt.decode(token, {complete: true})
            let res = await Util.decipher(data)
            return JSON.parse(res)
        } catch (error) {
            return false
        }
    }

    /**
     * 加密code
     * @param {object} data 
     */
    async sign_code (data) {
        let code  = await jwt.sign({
            exp: data.exp ? data.exp: (Date.now() + 1000 * 86400 * 1) / 1000,
            data: data.data
        }, sign_code)
        return code
    }
    /**
     * 验证code
     * 
     * @param {any} code 
     * @returns 
     * @memberof Jwt
     */
    async verify_code(code) {
        try {
            let data = await jwt.verify(code, sign_code)
            return data
        } catch (error) {
            console.trace(error)
            return false
        }
    }
    /**
     * 解密code
     * 
     * @param {any} code
     * @returns 
     * @memberof Jwt
     */
    async decode_code(code) {
        try {
            let data = jwt.decode(code, {complete: true})
            return data
        } catch (error) {
            return false
        }
    }
}

module.exports = new Jwt()